package com.touka.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.touka.common.Result;
import com.touka.entity.Employee;
import com.touka.mapper.EmployeeMapper;
import com.touka.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
  @Autowired
  private EmployeeService employeeService;
  @Autowired
  private EmployeeMapper employeeMapper;

  /**
   * 员工登录
   *
   * @param request
   * @param employee
   * @return
   */
  @PostMapping("/login")
  public Result<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
    // 1. 将页面提交的密码password进行md5加密处理
    String password = employee.getPassword();
    password = DigestUtils.md5DigestAsHex(password.getBytes());

    // 2. 根据页面提交的用户名username查询数据库
    Employee emp = employeeService.getOne(
            Wrappers.lambdaQuery(Employee.class)
                    .eq(Employee::getUsername, employee.getUsername())
    );

    // 3. 如果没有查询到则返回登录失败结果
    if (emp == null) {
      return Result.error("登录失败");
    }

    // 4. 密码比对，如果不一致则返回登录失败结果
    if (!emp.getPassword().equals(password)) {
      return Result.error("登录失败，密码错误");
    }

    // 5. 查看员工状态，如果已经禁用，则返回员工已禁用
    if (emp.getStatus() == 0) {
      return Result.error("账号已禁用");
    }

    // 6. 登录成功，将员工id存入并返回登录成功结果
    request.getSession().setAttribute("employee", emp.getId());
    return Result.success(emp);
  }

  /**
   * 员工退出
   *
   * @param request
   * @return
   */
  @PostMapping("/logout")
  public Result<String> logout(HttpServletRequest request) {
    // 清理Session中保存的当前登录员工的id
    request.getSession().removeAttribute("employee");
    return Result.success("退出成功");
  }

  /**
   * 新增员工
   *
   * @param employee
   * @return
   */
  @PostMapping
  public Result<String> save(HttpServletRequest request, @RequestBody Employee employee) {
    log.info("新增员工，员工信息，{}", employee);

    // 设置初始密码，并进行md5加密
    employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
    // employee.setCreateTime(LocalDateTime.now()); // 设置创建时间
    // employee.setUpdateTime(LocalDateTime.now()); // 设置更新时间
    // Long session = (Long) request.getSession().getAttribute("employee"); // 获取登录用户信息
    // employee.setCreateUser(session); // 设置创建人
    //employee.setUpdateUser(session); // 设置更新人

    boolean save = employeeService.save(employee); // 保存用户信息到数据库

    if (save) {
      return Result.success("新增成功");
    }
    return Result.error("新增失败");
  }

  /**
   * 分页查询员工
   *
   * @param page
   * @param pageSize
   * @param name
   * @return
   */
  @GetMapping("/page")
  public Result<Map<String, Object>> list(@DefaultValue("1") Long page, @DefaultValue("10") Integer pageSize, String name) {
    log.info("查询员工：{}，{}，{}", page, pageSize, name);
    Page<Employee> pageEmp = new Page<>(page, pageSize);

    Page<Employee> employeePage = employeeService.page(
            pageEmp,
            Wrappers.lambdaQuery(Employee.class)
                    // 查询条件
                    .like(StringUtils.isNotBlank(name), Employee::getName, name)
                    // 排序条件
                    .orderByDesc(Employee::getUpdateTime)
    );

    Map<String, Object> map = new HashMap<>();
    map.put("records", employeePage.getRecords()
            .stream()
            .map(employee -> {
              employee.setPassword("");
              return employee;
            })
            .toList());
    map.put("total", employeePage.getTotal());

    return Result.success(map);
  }

  /**
   * 根据Id修改员工
   *
   * @param request
   * @param employee
   * @return
   */
  @PutMapping
  public Result<String> update(HttpServletRequest request, @RequestBody Employee employee) {
    log.info("修改员工信息：{}", employee);
    Long empId = employee.getId();
    if (!StringUtils.isNotBlank(empId.toString())) {
      return Result.error("操作失败");
    }
//    LambdaUpdateWrapper<Employee> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//    lambdaUpdateWrapper.eq(Employee::getId, employee.getId())
//            .set(StringUtils.isNotBlank(employee.getUsername()), Employee::getUsername, employee.getUsername())
//            .set(StringUtils.isNotBlank(employee.getName()), Employee::getName, employee.getName())
//            .set(StringUtils.isNotBlank(employee.getPhone()), Employee::getPhone, employee.getPhone())
//            .set(StringUtils.isNotBlank(employee.getSex()), Employee::getSex, employee.getSex())
//            .set(StringUtils.isNotBlank(employee.getIdNumber()), Employee::getIdNumber, employee.getIdNumber())
//            .set(StringUtils.isNotBlank(employee.getStatus().toString()), Employee::getStatus, employee.getStatus());
//            .set(Employee::getUpdateTime, LocalDateTime.now())
//            .set(Employee::getUpdateUser, request.getSession().getAttribute("employee"));
//    boolean update = employeeService.update(lambdaUpdateWrapper);

    long id = Thread.currentThread().getId();
    log.info("线程Id：{}", id);

    boolean update = employeeService.updateById(employee);

    return update ? Result.success("修改成功") : Result.error("修改失败");
  }

  /**
   * 根据Id查询员工
   *
   * @param id
   * @return
   */
  @GetMapping("/{id}")
  public Result<Employee> getById(@PathVariable Integer id) {
    log.info("根据Id查询员工");
    Employee employee = employeeService.getById(id);
    return Result.success(employee);
  }
}
